package dao

import (
	"context"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"net/http"
	"prod/api/prod"
	"prod/internal/constant"
	"prod/internal/model"
	"prod/pkg/ecode"
)

func (d *Dao) GetTaskList(ctx context.Context, sgId, pStoreId uint32, nature prod.Nature,
	pageNo, pageSize uint32) (tasks []*model.Task, total uint32, err error) {
	db := d.TransContext(ctx).Model(&model.Task{}).Where(
		"sg_id = ? AND p_store_id = ? AND task_type = ?",
		sgId, pStoreId, int(nature))
	var rawTotal int64
	if err = db.Count(&rawTotal).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	total = uint32(rawTotal)
	if err = db.Order("id desc").Offset(int((pageNo - 1) * pageSize)).Limit(
		int(pageSize)).Find(&tasks).Error; err != nil {
		err = d.processSqlError(err)
	}
	return
}

func (d *Dao) GetTaskExcel(link string) (data []map[string]string, err error) {
	var (
		resp      *http.Response
		taskExcel *excelize.File
		sheet     [][]string
	)
	if resp, err = d.httpClient.Get(link); err != nil {
		err = ecode.AppendMessage(constant.ErrRemoteError, "下载excel失败")
		return
	}
	defer func() { _ = resp.Body.Close() }()
	if taskExcel, err = excelize.OpenReader(resp.Body); err != nil {
		err = ecode.AppendMessage(constant.ErrRemoteError, "加载excel失败")
		return
	}
	if sheet, err = taskExcel.GetRows("sheetName"); err != nil {
		err = ecode.AppendMessage(constant.ErrFileFormat, "找不到对应sheet")
		return
	}
	if len(sheet) < 2 {
		err = ecode.AppendMessage(constant.ErrFileFormat, "没有对应的商品行")
		return
	}
	data = make([]map[string]string, len(sheet))
	keyMap := make(map[int]string)
	for i, key := range sheet[0] {
		switch key {
		case "商品名称", "一级分类", "二级分类", "价格", "规格名", "属性":
			keyMap[i] = key
		}
	}
	if len(keyMap) != 6 {
		err = ecode.AppendMessage(constant.ErrFileFormat, "标题栏缺失关键字")
		return
	}
	for i, rows := range sheet[1:] {
		data[i] = make(map[string]string)
		for j, cell := range rows {
			if key, ok := keyMap[j]; ok {
				data[i][key] = cell
			}
		}
	}
	return
}
